package com.wuyou.simple;

/**
 * LongestCommonPrefix
 *
 * @Date 2024/12/17 16:51
 * @Author 无忧
 */
public class LongestCommonPrefix {


    public static void main(String[] args) {
        LongestCommonPrefix longestCommonPrefix = new LongestCommonPrefix();
        String[] strs = {"a"};

        System.out.println(longestCommonPrefix.longestCommonPrefix1(strs));
    }


    public String longestCommonPrefix1(String[] strs) {
        int strMinLengthIdx = 0, strMinLength = Integer.MAX_VALUE, finalIdx = 0;
        for (int i = 0; i < strs.length; i++) {
            if(strMinLength > strs[i].length()){
                strMinLength = strs[i].length();
                strMinLengthIdx = i;
            }
        }
        for (int i = 0; i < strMinLength; i++) {
            char c = strs[strMinLengthIdx].charAt(i);
            for (int j = 0; j < strs.length; j++) {
                if (strs[j].charAt(i) != c) {
                    return strs[strMinLengthIdx].substring(0, i);
                }
            }
            finalIdx ++;
        }
        return strs[strMinLengthIdx].substring(0, finalIdx);
    }
    public String longestCommonPrefix(String[] strs) {
        StringBuilder sb = new StringBuilder();
        int strMinLengthIdx = 0, strMinLength = Integer.MAX_VALUE;
        for (int i = 0; i < strs.length; i++) {
            if(strMinLength > strs[i].length()){
                strMinLength = strs[i].length();
                strMinLengthIdx = i;
            }
        }
        for (int i = 0; i < strMinLength; i++) {
            for (int j = 0; j < strs.length - 1; j++) {
                if (strs[j].charAt(i) != strs[j + 1].charAt(i)) {
                    return sb.toString();
                }
            }
            sb.append("" + strs[strMinLengthIdx].charAt(i));
        }
        return sb.toString();
    }
}
